/**
 * Created by baidm in 2020/11/21 on 9:39
 */
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
// let nums1 = [1, 3], nums2 = [2];
let nums1 = [1, 2], nums2 = [3, 4];
// let nums1 = [0,0], nums2 = [0,0];
// let nums1 = [], nums2 = [1];
// let nums1 = [2], nums2 = [];
// let nums1 = [0, 0, 0, 0, 0], nums2 = [-1, 0, 0, 0, 0, 0, 1];

let findMedianSortedArrays = function (nums1, nums2) {
    let concatArr = nums1.concat(nums2).sort((a, b) => a - b);
    let len = concatArr.length;
    if (!len) return 0;
    if (len < 2) return (concatArr[0]);
    let number = Math.floor(len / 2);
    if (len % 2 === 1) {
        return concatArr[number];
    } else {
        return (concatArr[number] + concatArr[number - 1]) / 2;
    }
};

// 时间复杂度O(log(m+n))
let findMedianSortedArrays2 = function (nums1, nums2) {
    let len = nums1.length + nums2.length;
    let indexArr = len % 2 === 1 ? [Math.floor(len / 2)] : [Math.floor(len / 2) - 1, Math.floor(len / 2)];
    let res = [], i = 0, j = 0;
    while (i + j <= len / 2) {
        if (nums1[i] === undefined) {
            res.push(nums2[j++]);
        } else if (nums2[j] === undefined) {
            res.push(nums1[i++]);
        } else {
            res.push(nums1[i] < nums2[j] ? nums1[i++] : nums2[j++]);
        }
    }
    return indexArr.length > 1 ? (res[indexArr[0]] + res[indexArr[1]]) / 2 : res[indexArr[0]];
};

// console.log(findMedianSortedArrays(nums1, nums2));
console.log(findMedianSortedArrays2(nums1, nums2));